package com.qidian.permission.service.impl;

import com.qidian.permission.entity.Role;
import com.qidian.permission.entity.User;
import com.qidian.permission.mapper.RoleMapper;
import com.qidian.permission.mapper.UserMapper;
import com.qidian.permission.service.RoleService;
import com.qidian.permission.util.PagerHelper;
import com.qidian.permission.util.PerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author 32郗建狄
 * @Company GX631
 * Time 2023/10/21 15:39
 * Description
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Override
    public PerResult selectById(Long roleId) {
        Role role = null;
        if ((role = roleMapper.selectById(roleId))!=null){
            return PerResult.ok(role);
        }
        return PerResult.empty();
    }

    @Override
    public PerResult addRole(Role role) {
        if (role != null && roleMapper.selectByRoleName(role.getRoleName()) != null){
            return PerResult.duplicate("该角色已存在");
        }
        return PerResult.updateIsOk(roleMapper.addRole(role));
    }

    @Override
    public PerResult selectByPage(Role role, int page, int limit) {
        PagerHelper<Role> pager = new PagerHelper<>();
        pager.setCurr(page);    //设置当前页
        pager.setLimit(limit);  //设置查询总页数
        pager.setTotal(roleMapper.selectCount(role));   //设置总页数
        pager.setData(roleMapper.selectByPage(role,(page - 1) * limit,limit));
        pager.setMaxPageNum((int)(Math.ceil(pager.getTotal() * 1.0 / limit)));
        return PerResult.ok(pager);
    }

    @Override
    public PerResult update(Role role) {
        // 校验是否重复
        Role roleTemp = roleMapper.selectByRoleName(role.getRoleName());
        if(roleTemp != null && !roleTemp.getRoleId().equals(role.getRoleId())){
            return PerResult.duplicate("角色名重复");
        }
        return PerResult.updateIsOk(roleMapper.update(role));
    }

    @Override
    public PerResult deleteByRoleId(Long roleId) {
        if (Objects.nonNull(roleId)){
            roleMapper.deteleByRoleId(roleId);
            return PerResult.ok();
        }
        return PerResult.empty();
    }

    @Override
    public PerResult deletesByRoleId(Long[] roleIds) {

        int count = roleMapper.deletesByRoleId(roleIds);
        return PerResult.ok(count+"");


    }
}
